package net.tycmc.cty.ctyms.timejob.iems.service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import com.tycmc.functions.util.MapGetter;

import net.tycmc.cty.ctyms.timejob.common.ListUtil;
import net.tycmc.cty.ctyms.timejob.iems.dao.ChangeInstallRecordDao;
import net.tycmc.cty.ctyms.timejob.iems.thread.ChangeInstallRecordRunner;

public class ChangeInstallRecordService {
	private ChangeInstallRecordDao cird;
	public  static  List<String>listsql=new Vector<String>();
	public ChangeInstallRecordDao getCird() {
		return cird;
	}

	public void setCird(ChangeInstallRecordDao cird) {
		this.cird = cird;
	}
	public void startWork(String Msgtime){
		//建立线程池 （固定线程数）
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		//获取发动机序列号变更的记录
		List<Map<String,Object>>listInstall=cird.getAllChangeRecord(Msgtime);
		//按照设备id分组
		Map<String,List<Map<String,Object>>>mapInstall=new ListUtil().groupBy("vehicleid", listInstall);
		//sql集合
		Set<String>key=mapInstall.keySet();
		CountDownLatch threadsSignal = new CountDownLatch(listInstall.size());
		for(Iterator<String>it=key.iterator();it.hasNext();){
			String vclkey=it.next();
			//获取每台车的发动机序列号变更记录集合，此集合是按照时间正序排序
			List<Map<String,Object>>listRecord=mapInstall.get(vclkey);
			if(null!=listRecord&&listRecord.size()>0){
				//上一条记录的发动机序列号
				String preesn="";
				for(int i=0;i<listRecord.size();i++){//开始遍历这些集合
					Map<String,Object>mapresult=listRecord.get(i);//包含设备id、序列号变更时间
					mapresult.put("statetime",Msgtime);
					//将前一条的发动机序列号存储于map
					if(i==0){
						mapresult.put("preesn","");
					}else{
						mapresult.put("preesn",preesn);
					}
					preesn=MapGetter.getString(mapresult,"esnno");//序列号
					//将后一条的发动机变更时间作为结束时间
					if(i<listRecord.size()-1){
						String msgtime=MapGetter.getString(listRecord.get(i+1),"msgtime");//发动机序列号变更时间
						mapresult.put("endmsgtime",msgtime);
					}
					//开启线程
					executorService.submit(new ChangeInstallRecordRunner(mapresult,cird,threadsSignal));
				}
			}
		}
		try {
			threadsSignal.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//执行sql插入操作
		if(this.listsql.size()>0){
			cird.execInstallRecordSql(this.listsql);
		}
	}
}
